package com.sjsu.aws.rendavu;

import java.util.UUID;
/**
 * 
 * @author Shweta Dattatreya
 *
 */
public class Client extends Thread {
	private AWSClient client;
	private String id;
	private long timeout;
	private long lifeTime = 60 * 1000; 	// 60 s
	private long expiry;
	private String name;
/**
 * 	
 * @param numWorkers
 * @throws Exception
 */
	public Client(int numWorkers) throws Exception {
		id = UUID.randomUUID().toString();
		client = AWSClient.getInstance();
		timeout = 30 * 1000;	// 30s
		expiry = System.currentTimeMillis() + lifeTime;
		synchronized(client) {
			client.insertItem(id, getExpiryTS(), "NA", "NA");
		}
		for (int i = 1; i < numWorkers+1; i++) {
			System.out.println("Worker" + i + "entering the process and reading Master Address");
			createWorker();
			
		}
		createMaster();
	}
	
	String getExpiryTS() {
		return String.valueOf(System.currentTimeMillis() + timeout);
	}
/**
 * 	
 * @throws Exception
 */
	void createMaster() throws Exception {
		Master master = new Master(id);
		master.start();
	}
/**
 * 	
 * @throws Exception
 */
	void createWorker() throws Exception {
		Worker worker = new Worker(id);
		worker.start();
	}
	
	public void run() {
		try {
			if (expiry > System.currentTimeMillis()) {
				Thread.sleep(10 * 1000);
				client.updateTS(id, getExpiryTS());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
